package com.yunjinsuke.recharge.controller;

import com.alibaba.fastjson.JSONObject;
import com.yunjinsuke.recharge.common.ObjectId;
import com.yunjinsuke.recharge.controller.api.APIEnum;
import com.yunjinsuke.recharge.controller.api.ApiResponse;
import com.yunjinsuke.recharge.redis.RedisKeyUtil;
import com.yunjinsuke.recharge.redis.RedisUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;


/**
 * 授权
 */
@RestController
@RequestMapping("auth")
public class AuthController {

    private final RedisUtil redisUtil;

    public AuthController(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 获取访问Token
     *
     * @param mchId  商户号
     * @param mchKey 商户密钥
     * @return 访问Token
     */
    @GetMapping("accessToken")
    public ApiResponse accessToken(@RequestParam("mchId") String mchId,
                                   @RequestParam("mchKey") String mchKey) {
        if (redisUtil.hasKey(RedisKeyUtil.merchantKey(mchId, mchKey))) {

            String accessToken = ObjectId.getId();
            redisUtil.set(RedisKeyUtil.merchantKey(mchId, mchKey), accessToken);
            // 2个小时有效
            redisUtil.set(RedisKeyUtil.accessTokenKey(accessToken), mchId, 2 * 60 * 60);
            return new ApiResponse(new JSONObject() {{
                put("accessToken", accessToken);
            }});
        } else {
            return new ApiResponse(APIEnum.INVALID_REQUEST, "商户号或商户密钥有误");
        }
    }

}
